import React, { memo } from 'react'
import type { FC, ReactNode } from 'react'
import { DatePicker, ConfigProvider } from 'antd'
import type { DatePickerProps, GetProps } from 'antd'
import locale from 'antd/locale/zh_CN'
import 'dayjs/locale/zh-cn'

import fetchData from '../../../request'
import { useMyDispatch, useMySelector, MyShallEqual } from '../../../store'
import { setEndTime } from '../../../store/modules/create'
import dayjs from 'dayjs'

type RangePickerProps = GetProps<typeof DatePicker.RangePicker>

interface IProps {
  children?: ReactNode
}

const TimeSelector: FC<IProps> = () => {
  const dispatch = useMyDispatch()
  const { endtime, id } = useMySelector(
    (state) => ({
      endtime: state.code.endTime,
      id: state.codeall.id
    }),
    MyShallEqual
  )
  const onOk = (
    value: DatePickerProps['value'] | RangePickerProps['value']
  ) => {
    console.log('onOk: ', value)
  }
  return (
    <ConfigProvider
      locale={locale}
      theme={{
        token: {
          colorPrimary: '#d0e750'
        }
      }}
    >
      <DatePicker
        showTime
        placeholder={endtime}
        value={
          endtime === '永久有效'
            ? undefined
            : dayjs(endtime, 'YYYY-MM-DD HH:mm:ss')
        }
        onChange={(value, dateString) => {
          if (dateString) {
            dispatch(setEndTime(dateString))
            fetchData('/update', { id, endTime: dateString }, 'POST')
          } else {
            dispatch(setEndTime('永久有效'))
            fetchData('/update', { id, endTime: '永久有效' }, 'POST')
          }
        }}
        onOk={onOk}
      />
    </ConfigProvider>
  )
}

export default memo(TimeSelector)
